<template>
  <div>
    <a-mentions
        style="margin-top: 10px"
        v-model:value="sourceText"
        rows="10"
        placeholder="在这里粘贴您需要格式化的代码"
    >
    </a-mentions>
    <a-row style="margin:10px 0px;" align="middle">
      <a-col :span="18">
        <a-radio-group v-model:value="codeType">
          <a-radio value="js">JavaScript</a-radio>
          <a-radio value="html">HTML</a-radio>
          <a-radio value="css">CSS</a-radio>
          <a-radio value="sql">SQL</a-radio>
        </a-radio-group>
      </a-col>
      <a-col :span="6" style="text-align: right">
        <a-button type="primary" style="background: #f0ad4e;color:#fff;border-color:#eea236" @click="copyCode()">复制结果</a-button>&nbsp;
        <a-button type="primary" style="background: #5cb85c;color:#fff;border-color:#4cae4c" @click="formats()">格式化</a-button>
      </a-col>

    </a-row>
    <pre><code v-html="highlightedCode()"></code></pre>
  </div>

</template>

<script lang="ts" setup>
import {onMounted, ref} from "vue";
import beautify from 'js-beautify';
import hljs from 'highlight.js';
import {format} from 'sql-formatter';
import 'highlight.js/styles/github.css';
import {message} from "ant-design-vue";
const sourceText = ref("")
const formattedCode = ref("")
const codeType = ref("js");

//复制代码
const copyCode=()=>{
  navigator.clipboard.writeText(formattedCode.value)
  message.success("已复制到剪切板")
}

//高亮代码
const highlightedCode=()=>{
  let codeHigh =hljs.highlight(codeType.value, formattedCode.value).value;
  console.log(codeHigh)
  return codeHigh;
}

//格式化
const formats=()=>{
  let options = {

  }
  let formatted  ="";
  switch (codeType.value){
    case "js":
      options={
        "indent_size": 2,
        "indent_char": " ",
        "indent_with_tabs": false,
        "eol": "\n",
        "end_with_newline": false,
        "space_in_paren": false
      }
      formatted =beautify.js_beautify(sourceText.value,options)
      break;
    case "html":
      options={
        "indent_size": 2,
        "indent_char": " ",
        "indent_with_tabs": false,
        "eol": "\n",
        "end_with_newline": false,
        "wrap_line_length": 0
      }
      formatted =beautify.html_beautify(sourceText.value,options)
      break;
     case "css":
       options={
         "indent_size": 2,
         "indent_char": " ",
         "indent_with_tabs": false,
         "eol": "\n",
         "end_with_newline": false,
         "newline_between_rules": false
       }
       formatted =beautify.css_beautify(sourceText.value,options)
      break;
     case "sql":
       formatted =format(sourceText.value, { language: 'mysql' })
  }
  formattedCode.value = formatted;
}

onMounted(() => {
})

</script>

<style scoped>
pre {
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 5px;
}
code {
  color: #333;
  font-family: Consolas, monospace;
}






</style>
